package cn.itdm.dislock.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

@Slf4j
@Controller
public class DisLockController {
    @Autowired
    private RedisLockRegistry redisLockRegistry;

    @ResponseBody
    @GetMapping("test")
    public String test() throws InterruptedException {
        Lock lock = redisLockRegistry.obtain("lock");
        boolean b1 = lock.tryLock(3, TimeUnit.SECONDS);
        System.out.println("b1 is :"+b1+",time="+new Date());
        TimeUnit.SECONDS.sleep(5);

        boolean b2 = lock.tryLock(3, TimeUnit.SECONDS);
        System.out.println("b2 is :"+b2+",time="+new Date());

        lock.unlock();
        lock.unlock();
        return "ok";
    }
}

